package com.ruoyi.web.controller.tool;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class QueryEncryptionUtil {

    // AES密钥长度
    private static final int AES_KEY_SIZE = 128;

    // 密钥（在实际应用中，应通过安全方式获取密钥，而不是硬编码）
    // 注意：这里的密钥长度是16字节（128位），符合AES-128的要求
    private static final byte[] SECRET_KEY_BYTES = "0123456789abcdef".getBytes(); // 示例密钥，16字节

    // 将密钥字节数组转换为SecretKeySpec对象
    private static final SecretKeySpec SECRET_KEY_SPEC = new SecretKeySpec(SECRET_KEY_BYTES, "AES");

    // 加密方法
    public static String encrypt(String data) throws Exception {
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, SECRET_KEY_SPEC);
        byte[] encryptedData = cipher.doFinal(data.getBytes("UTF-8"));
        return Base64.getEncoder().encodeToString(encryptedData);
    }

    // 解密方法
    public static String decrypt(String encryptedData) throws Exception {
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, SECRET_KEY_SPEC);
        byte[] decodedData = Base64.getDecoder().decode(encryptedData);
        byte[] decryptedData = cipher.doFinal(decodedData);
        return new String(decryptedData, "UTF-8");
    }

    // 生成一个新的AES密钥（通常用于测试或初始化，不建议在生产环境中使用）
    public static String generateSecretKey() throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(AES_KEY_SIZE);
        SecretKey secretKey = keyGenerator.generateKey();
        return Base64.getEncoder().encodeToString(secretKey.getEncoded());
    }

    // 主方法，用于测试加密和解密功能
    public static void main(String[] args) {
        try {
            String originalQuery = "SELECT * FROM users WHERE id = ? AND password = ?";
            System.out.println("Original Query: " + originalQuery);

            // 加密查询
            String encryptedQuery = encrypt(originalQuery);
            System.out.println("Encrypted Query: " + encryptedQuery);

            // 解密查询
            String decryptedQuery = decrypt(encryptedQuery);
            System.out.println("Decrypted Query: " + decryptedQuery);

            // 生成一个新的AES密钥（仅用于示例）
            String newSecretKey = generateSecretKey();
            System.out.println("Generated Secret Key: " + newSecretKey);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}